import asyncio
import websockets
import struct


async def handler(websocket, path):
    # 接收客户端消息
    client_msg = await websocket.recv()
    print(f"收到客户端消息: {client_msg}")

    # 构造测试二进制数据
    status_code = 256
    measurements = [0.5, 1.0, 5.0]

    # 小端序打包
    binary_data = struct.pack(
        "<HI" + "f" * len(measurements),
        status_code,
        len(measurements),
        *measurements
    )

    # 发送二进制响应
    await websocket.send(binary_data)
    print(f"已发送二进制响应 ({len(binary_data)} bytes)")


start_server = websockets.serve(handler, "127.0.0.1", 8080)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()